<template>
  <div v-if="activity">
    <n-space vertical size="large">
      <n-card>
        <template #header>
          <n-space align="center">
            <n-button text @click="router.back()">
              <n-icon size="20"><ArrowBackOutline /></n-icon>
            </n-button>
            <span>{{ activity.title }}</span>
            <n-tag v-if="activity.status === 'RECRUITING'" type="success">报名中</n-tag>
            <n-tag v-else-if="activity.status === 'IN_PROGRESS'" type="info">进行中</n-tag>
            <n-tag v-else-if="activity.status === 'COMPLETED'" type="default">已完成</n-tag>
          </n-space>
        </template>

        <n-descriptions bordered :column="2">
          <n-descriptions-item label="活动地点">
            <n-text>{{ activity.location }}</n-text>
          </n-descriptions-item>
          <n-descriptions-item label="活动类别">
            <n-tag>{{ activity.category }}</n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="开始时间">
            {{ formatDate(activity.startTime) }}
          </n-descriptions-item>
          <n-descriptions-item label="结束时间">
            {{ formatDate(activity.endTime) }}
          </n-descriptions-item>
          <n-descriptions-item label="报名人数">
            {{ activity.currentParticipants }} / {{ activity.maxParticipants || '不限' }}
          </n-descriptions-item>
          <n-descriptions-item label="积分奖励">
            <n-text type="success">{{ activity.pointsReward }} 积分</n-text>
          </n-descriptions-item>
          <n-descriptions-item label="活动描述" :span="2">
            {{ activity.description }}
          </n-descriptions-item>
        </n-descriptions>

        <template #action>
          <n-space>
            <n-button
              v-if="activity.status === 'RECRUITING' && !hasEnrolled"
              type="primary"
              @click="handleEnroll"
            >
              立即报名
            </n-button>
            <n-button
              v-if="hasEnrolled && enrollment?.status !== 'CANCELLED'"
              @click="handleCancelEnroll"
            >
              取消报名
            </n-button>
            <n-button
              v-if="activity.status === 'COMPLETED' && canEvaluate"
              type="success"
              @click="evaluationModalVisible = true"
            >
              我要评价
            </n-button>
          </n-space>
        </template>
      </n-card>

      <n-card title="活动评价">
        <n-list hoverable>
          <n-list-item v-for="evaluation in evaluations" :key="evaluation.id">
            <n-thing>
              <template #avatar>
                <n-avatar>{{ evaluation.userId }}</n-avatar>
              </template>
              <template #header>
                <n-rate readonly :value="evaluation.rating" size="small" />
              </template>
              <template #description>
                <n-text depth="3">{{ formatDate(evaluation.createTime) }}</n-text>
              </template>
              {{ evaluation.content }}
            </n-thing>
          </n-list-item>
        </n-list>
        <n-empty v-if="!evaluations.length" description="暂无评价" />
      </n-card>
    </n-space>

    <n-modal v-model:show="evaluationModalVisible" preset="dialog" title="评价活动">
      <n-form :model="evaluationForm">
        <n-form-item label="评分">
          <n-rate v-model:value="evaluationForm.rating" />
        </n-form-item>
        <n-form-item label="评价内容">
          <n-input
            v-model:value="evaluationForm.content"
            type="textarea"
            placeholder="请分享您的参与体验"
            :rows="4"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="evaluationModalVisible = false">取消</n-button>
          <n-button type="primary" @click="submitEvaluation">提交评价</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getActivityDetail, enrollActivity, cancelEnrollment, getUserEnrollments } from '@/api/activity'
import { getActivityEvaluations, createEvaluation } from '@/api/evaluation'
import { ArrowBackOutline } from '@vicons/ionicons5'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const activity = ref(null)
const evaluations = ref([])
const enrollment = ref(null)
const evaluationModalVisible = ref(false)
const evaluationForm = reactive({
  rating: 5,
  content: ''
})

const hasEnrolled = computed(() => !!enrollment.value)
const canEvaluate = computed(() => {
  return hasEnrolled.value && 
         enrollment.value?.status === 'COMPLETED' &&
         !evaluations.value.some(e => e.userId === Number(userStore.userId))
})

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

const loadActivity = async () => {
  try {
    const res = await getActivityDetail(route.params.id)
    activity.value = res.data
    
    // 加载评价
    const evalRes = await getActivityEvaluations(route.params.id)
    evaluations.value = evalRes.data || []
    
    // 检查是否已报名
    const enrollRes = await getUserEnrollments(userStore.userId)
    enrollment.value = enrollRes.data?.find(e => e.activityId === Number(route.params.id))
  } catch (error) {
    console.error('加载活动详情失败:', error)
  }
}

const handleEnroll = async () => {
  try {
    await enrollActivity(route.params.id, {
      userId: userStore.userId,
      reason: ''
    })
    window.$message?.success('报名成功')
    loadActivity()
  } catch (error) {
    console.error('报名失败:', error)
  }
}

const handleCancelEnroll = async () => {
  try {
    await cancelEnrollment(route.params.id, {
      userId: userStore.userId
    })
    window.$message?.success('已取消报名')
    loadActivity()
  } catch (error) {
    console.error('取消报名失败:', error)
  }
}

const submitEvaluation = async () => {
  try {
    await createEvaluation({
      activityId: route.params.id,
      userId: userStore.userId,
      rating: evaluationForm.rating,
      content: evaluationForm.content
    })
    window.$message?.success('评价成功')
    evaluationModalVisible.value = false
    loadActivity()
  } catch (error) {
    console.error('评价失败:', error)
  }
}

onMounted(() => {
  loadActivity()
})
</script>

